using System;
using System.Collections.Generic;
using System.Linq;
using GameEngine.Linq;
using Microsoft.Xna.Framework;

namespace GameEngine.Units
{
	public class Item : Grounded
	{
		public ICollection<Unit> pickableBy;
		private ItemType type;

		public Item(ItemType type, World world)
			: base(type, world)
		{
			this.type = type;
			this.pickableBy = pickableBy;
		}

		public ICollection<Unit> PickableBy { get; set; }
		public bool AutoPick
		{
			get
			{
				return this.type.AutoPick;
			}
		}
		public Func<Unit, bool> UnitFilter
		{
			get
			{
				return this.type.UnitFilter;
			}
		}
		public ICollection<Unit> TypePickableBy
		{
			get
			{
				return this.type.PickableBy;
			}
		}
		public bool IsPicked { get; internal set; }

		internal override void Update(GameTime gameTime)
		{
			if (this.AutoPick && !this.IsPicked)
			{
				IEnumerable<Unit> pickingUnits;
				if (this.PickableBy != null || this.TypePickableBy != null)
				{
					pickingUnits = GameEngine.Linq.Enumerable.Append(this.PickableBy, this.TypePickableBy);
				}
				else
				{
					pickingUnits = this.World.Units;
				}
				if (this.UnitFilter != null)
				{
					pickingUnits = pickingUnits.Where(this.UnitFilter);
				}
				foreach (Unit unit in pickingUnits)
				{
					if (this.Radius + unit.Radius >= Vector3.Distance(this.Position, unit.Position))
					{
						this.World.Pick(unit, this);
						break;
					}
				}
			}
		}
	}
}
